package com.manor.main.activity

import android.content.Context
import android.content.Intent
import android.text.Editable
import android.text.Selection
import android.text.TextWatcher
import com.manor.common.activity.AbsActivity
import com.manor.common.interfaces.CommonCallback
import com.manor.main.R
import com.manor.main.http.MainHttpUtil
import kotlinx.android.synthetic.main.activity_ed_autograph.*

/*
 * 修改个人简介
 */
class EdAutographActivity :AbsActivity(){
    override fun getLayoutId(): Int {
        return R.layout.activity_ed_autograph
    }

    companion object {
        fun forward(context: Context, msg:String) {
            val intent = Intent(context, EdAutographActivity::class.java)
            intent.putExtra("msg",msg)
            context.startActivity(intent)
        }
    }


    override fun main() {
        super.main()
        var msg = intent?.extras?.getString("msg")
        if(msg?.length!! >0){
            ed_code.setText(msg)
            tvCount.text = msg.toString().length.toString()+ "/40"
        }
        ed_code.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                var editable = ed_code.text
                val len = editable.length
                //显示还可以输入多少字
                tvCount.text = len.toString()+ "/40"
                if (len > 40) {
                    var selEndIndex = Selection.getSelectionEnd(editable)
                    val str = editable.toString()
                    //截取新字符串
                    val newStr = str.substring(0, 40)
                    ed_code.setText(newStr)
                    editable = ed_code.text

                    //新字符串的长度
                    val newLen = editable.length
                    //旧光标位置超过字符串长度
                    if (selEndIndex > newLen) {
                        selEndIndex = editable.length
                    }
                    //设置新光标所在的位置
                    Selection.setSelection(editable, selEndIndex)
                }else{
                    if(len>0){
                        tv_btn.setImageResource(R.mipmap.pic_ed_btns);
                    }else{
                        tv_btn.setImageResource(R.mipmap.pic_ed_btn);
                    }
                }
            }

            override fun afterTextChanged(s: Editable) {}
        })
        tv_btn.setOnClickListener {
            setUserInfo("signature", ed_code.text.toString(), object : CommonCallback<Boolean>() {
                override fun callback(bean: Boolean?) {
                    if (bean!!) {
                        finish()
                    }
                }

            })
        };
    }
     fun setUserInfo(k: String, v: String, commonCallback: CommonCallback<Boolean>?) {
        MainHttpUtil.editUserInfo(k, v, commonCallback)
    }

}